/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\QuotaManage\StockCheck\List\component\InventoryModal.tsx
 * @Date: 2022-05-23 19:44:59
 * @LastEditTime: 2022-05-24 17:13:50
 */

import { UdTable } from '@/lib'
import React, { PureComponent } from 'react'
import dayjs from 'dayjs'

type IProps = {
  brandList: any[]
  [key: string]: any
}

type IState = {
  selectedRowKeys: number[]
  selectedRows: Record<string, any>[]
}

export default class InventoryModal extends PureComponent<IProps, IState> {
  private dataSource = this.props.brandList
  state: IState = {
    selectedRowKeys: [],
    selectedRows: [],
  }
  componentDidMount(): void {
    this.props.getHandler && this.props.getHandler(() => this.state.selectedRows.map(item=>{
      return { ...item, cycleText: this.formatCycleText(item) }
    }))
  }

  private onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys,
      selectedRows,
    })
  }

  private formatCycleText = (record: Record<string, any>): string => {
    let cycleText: string
    let currentMonth = dayjs().month() + 1
    for (let item of record.inventoryDateMonths) {
      if (item.month === currentMonth) {
        if (record.inventoryType === 'WEEKLY') {
          let currentWeek = dayjs().day() + 1
          for (let weekItem of item.weeklys) {
            if (weekItem.week === currentWeek) {
              const { weekName, weekStartTime, weekEndTime } = weekItem
              let startDay = dayjs(weekStartTime).format('DD')
              let endDay = dayjs(weekEndTime).format('DD')
              cycleText = `${weekName}(${startDay}~${endDay})`
              break
            }
          }
        } else {
          cycleText = item.monthName
        }
        break
      }
    }
    return cycleText
  }

  render() {
    let { selectedRowKeys } = this.state
    let columns: any[] = [
      { title: '公司编码', dataIndex: 'brandCode', key: 'brandCode', minWidth: '160px' },
      { title: '品牌公司', dataIndex: 'brandNameShort', key: 'brandNameShort', minWidth: '160px' },
      { title: '盘点时间', dataIndex: 'inventoryTypeName', key: 'inventoryTypeName', minWidth: '160px' },
      {
        title: '盘点周期',
        dataIndex: 'cycleText',
        key: 'cycleText',
        minWidth: '160px',
        render: (text, record) => {
          return this.formatCycleText(record)
        },
      },
    ]
    return (
      <UdTable
        dataSource={this.dataSource}
        columns={columns}
        rowKey="brandCode"
        pagination={false}
        rowSelection={{
          type: 'radio',
          selectedRowKeys: selectedRowKeys,
          onChange: this.onSelectChange,
        }}
      />
    )
  }
}
